//
//  CCRPhoneViewModel.m
//  Activity
//
//  Created by coco on 15/5/7.
//  Copyright (c) 2015年 coco. All rights reserved.
//

#import "CCRPhoneViewModel.h"
#import <AVOSCloud/AVOSCloud.h>
@interface CCRPhoneViewModel()
@property (nonatomic, strong) id<RACSubscriber> subscriber;
@end
@implementation CCRPhoneViewModel

- (id) init {
  if (self = [super init]) {
    _nextSignal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
      _subscriber = subscriber;
      return [RACDisposable disposableWithBlock:^{
        _subscriber = nil;
      }];
    }];
    _nextCommand = [[RACCommand alloc] initWithEnabled:
                    [RACSignal combineLatest:@[RACObserve(self, isAgree), RACObserve(self, text)]
                                      reduce:^(NSNumber *agree, NSString *text){
                                        return @(([agree intValue] == 1) && (text.length > 0));
                                      }] signalBlock:^RACSignal *(id input) {
                                        [_subscriber sendNext:[CCError errorWithCode:1 des:@"请稍候"]];
                                        [AVOSCloud requestSmsCodeWithPhoneNumber:self.text callback:^(BOOL succeeded, NSError *error) {
                                          if (succeeded) {
                                            [_subscriber sendNext:[CCError errorWithCode:0 des:@"成功"]];
                                          } else if([error.userInfo[@"code"] intValue] == 127){
                                            [_subscriber sendNext:[CCError errorWithCode:2 des:@"请检查手机号码是否正确"]];
                                          }
                                        }];
                                        return [RACSignal empty];
                                      }];
  }
  return self;
}

- (void) dealloc {
  NSLog(@"rphone dealloc");
}
@end
